

class ListNode {
      int val;
      ListNode next;
     ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
  }
public class Day13 {
    public static void main(String[] args) {

    }
    public ListNode swapPairs(ListNode head) {
        if(head == null || head.next == null) return head;
        //1.交换前面两个结点
        ListNode slow = head;
        ListNode fast = head.next;
        slow.next = fast.next;
        fast.next = slow;
        ListNode ret = fast;
        ListNode tmp = slow;
        slow = slow.next;
        if(slow != null) fast = slow.next;
        //2.交换后续结点
        while(slow != null && fast != null) {
            tmp.next = fast;
            slow.next = fast.next;
            fast.next = slow;
            tmp = slow;
            slow = slow.next;
            if(slow != null) fast = slow.next;
        }
        return ret;
    }
}
